/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.settings;

import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.io.ZipUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarOutputStream;

public class ExportAllSettingsAction extends AnAction {
    private Logger logger = Logger.getInstance(getClass().getName());

    public void actionPerformed(AnActionEvent e) {
        Project project = DataKeys.PROJECT.getData(e.getDataContext());
        logger.info("project = " + project);
        ApplicationManager.getApplication().saveSettings();
        final SettingsChecker checker = SettingsChecker.getInstance(project);
        final File pluginsDir = new File(PathManager.getPluginsPath());
        logger.info("checker = " + checker.getSettingsFile());
        final File exportFile = new File(checker.getSettingsFile());
        try {
            JarOutputStream jaroutputstream = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(exportFile)));
            File file1 = new File(PathManager.getConfigPath());
            Set addedFiles = new HashSet();
            FileFilter fileFilter = new FileFilter() {
                public boolean accept(File file) {
                    if (file.getName().endsWith(".key")) {
                        return false;
                    }
                    try {
                        return !FileUtil.isAncestor(pluginsDir, file, false);
                    } catch (IOException e1) {
                        logger.error(e1);
                        return false;
                    }
                }
            };
            ZipUtil.addDirToZipRecursively(jaroutputstream, exportFile, file1, "", fileFilter, addedFiles);
//            File intelllijFile = new File(FileUtil.getTempDirectory(), "IntelliJ IDEA Global Settings");
//            intelllijFile.createNewFile();
//            intelllijFile.deleteOnExit();
//            ZipUtil.addFileToZip(jaroutputstream, intelllijFile, "IntelliJ IDEA Global Settings",
//                    addedFiles, null);
            jaroutputstream.close();
            final File dest = new File(checker.getPluginsDirectory());
            new DirectorySync().sync(new File(PathManager.getPluginsPath()), dest);
            Messages.showMessageDialog("Settings exported successfully.", IdeBundle.message("title.export.successful", new Object[0]),
                    Messages.getInformationIcon());
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                public void run() {
                    checker.manualChange();
                    refreshFile(exportFile, false);
                    refreshFile(dest, true);
                }
            });
        }
        catch (IOException ioexception) {
            Messages.showErrorDialog(IdeBundle.message("error.writing.settings", new Object[]{
                    ioexception.toString()
            }), IdeBundle.message("title.error.writing.exportFile", new Object[0]));
        }
    }

    private void refreshFile(File exportFile, boolean recursive) {
        VirtualFile fileByIoFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(exportFile);
        if (fileByIoFile != null) {
            fileByIoFile.refresh(false, recursive);
        } else {
            logger.info("Can't find file " + exportFile);
        }
    }
}
